<template>
  <div class="register-container">
    <a-card class="register-card" title="用户注册">
      <a-form :model="form" layout="vertical" @finish="handleRegister">
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="form.username" placeholder="请输入用户名" />
        </a-form-item>
        
        <a-form-item
          label="邮箱"
          name="email"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' }
          ]"
        >
          <a-input v-model:value="form.email" placeholder="请输入邮箱" />
        </a-form-item>
        
        <a-form-item
          label="密码"
          name="password"
          :rules="[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码至少6个字符' }
          ]"
        >
          <a-input-password v-model:value="form.password" placeholder="请输入密码" />
        </a-form-item>
        
        <a-form-item
          label="确认密码"
          name="confirmPassword"
          :rules="[
            { required: true, message: '请确认密码' },
            { validator: validateConfirmPassword }
          ]"
        >
          <a-input-password v-model:value="form.confirmPassword" placeholder="请再次输入密码" />
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit" block :loading="loading">注册</a-button>
        </a-form-item>
        
        <div class="login-link">
          已有账号? <router-link to="/login">立即登录</router-link>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { register } from '@/api/auth';

const router = useRouter();
const loading = ref(false);

const form = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
});

// 验证确认密码
const validateConfirmPassword = async (rule, value) => {
  if (value !== form.value.password) {
    throw new Error('两次输入的密码不一致');
  }
};

const handleRegister = async () => {
  loading.value = true;
  try {
    await register({
      username: form.value.username,
      email: form.value.email,
      password: form.value.password
    });
    
    message.success('注册成功，请登录');
    router.push('/login');
  } catch (error) {
    console.error('注册失败:', error);
    message.error('注册失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.register-card {
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-link {
  text-align: center;
  margin-top: 16px;
}
</style> 